/**
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2012 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */
package org.pz.platypus;

import static com.google.common.base.Preconditions.checkNotNull;

import org.pz.platypus.commandTypes.*;
import org.pz.platypus.exceptions.InvalidConfigFileException;

import java.io.File;
import java.util.Enumeration;

/**
 * @author alb
 */
public class CommandTableLoader
{
    GDD gdd;
    CommandTable ct;

    public CommandTableLoader( GDD Gdd )
    {
        gdd = checkNotNull( Gdd );
        ct = checkNotNull( gdd.commandTable, "Command table in CommandTableCommandLoader is null" );
    }

    public void load( final String filename )
    {
        checkNotNull( filename);
        File commandFile = new File( filename );
        if( ! ( commandFile.isFile() && commandFile.canRead() )) {
            throw new InvalidConfigFileException( gdd.getLit( "ERROR.MISSING_COMMAND_FILE" + " " + filename ));
        }

        PropertyFile pf = new PropertyFile( filename );
        pf.load();
        loadCommands( pf.getKeys(), pf );

        gdd.diag( "Command table in Platypus loaded with " + ct.size() + " commands" );
    }

    protected void loadCommands( final Enumeration<Object> commands, PropertyFile pf )
    {
        while( commands.hasMoreElements() ) {
            String root = (String) commands.nextElement();
            String commandDetails = pf.lookup( root );
            loadOneCommand( root, commandDetails );
        }
    }

    protected void loadOneCommand( String cRoot, String cDetails )
    {
        char[] attribs = cDetails.toCharArray();
        switch( attribs[0] )
        {
            case '0':   // commands with 0 parameters
                ct.add( new Command0( cRoot, attribs[1] ));
                break;

            case 's':   // commands with 1 parameter consisting of a string
                ct.add( new CommandS( cRoot, attribs[1] ));
                break;

            case 'v':   // commands with 1 parameter consisting of a value
                ct.add( new CommandV( cRoot, attribs[1] ));
                break;

            case 'r':   // replacement command (it's an alias for an individual family command)
               ct.add( new CommandR( cRoot, cDetails, ct )); //Commented out to shut up error msg in migration to Platypus-3
                break;

            default:
                gdd.log.warning( gdd.getLit( "ERROR.INVALID_COMMAND_FILE_ENTRY" ) +
                        cRoot + " " + gdd.getLit( "IGNORED" ));
        }
    }
}
